<template>
  <div class="login-page" @mousemove="handleMouseMove">
    <!-- 背景图片 -->
    <div class="login-bg"></div>

    <!-- 品牌信息 -->
    <div class="brand-info">
      <img src="/transparentLogo.png" alt="系统Logo" class="brand-logo" />
      <div class="brand-slogan">
        <!-- <p class="slogan-text">智慧校园，管理未来</p>
        <p class="slogan-subtitle">高效、安全、智能的学生管理平台</p> -->
      </div>
    </div>

    <!-- 登录卡片 -->
    <div class="login-card">
      <div class="login-header">
        <h2 class="login-title">学生管理系统</h2>
        <!-- 眼部跟踪效果 -->
        <div class="eyes-container">
          <div class="eye left-eye" ref="leftEye">
            <div class="pupil" :style="leftPupilStyle"></div>
          </div>
          <div class="eye right-eye" ref="rightEye">
            <div class="pupil" :style="rightPupilStyle"></div>
          </div>
        </div>
      </div>

      <!-- 登录表单：所有单标签均用自闭合语法 -->
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form" label-position="left"
        label-width="80px">
        <!-- 用户名输入框：修复标签闭合（加 /） -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名（3-20个字符）" :prefix-icon="User"
            :disabled="loading" /> <!-- 关键：这里加 / 自闭合 -->
        </el-form-item>

        <!-- 密码输入框：同样修复标签闭合 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码（至少6个字符）" :prefix-icon="Lock"
            :disabled="loading" show-password @focus="handlePasswordFocus" @blur="handlePasswordBlur" />
          <!-- 关键：加 / 自闭合 -->
        </el-form-item>

        <!-- 记住我：el-checkbox 是双标签，需正确闭合 -->
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" :disabled="loading">
            我已阅读并同意
            <el-link type="primary">用户协议</el-link>
            和
            <el-link type="primary">隐私政策</el-link>
          </el-checkbox> <!-- 双标签正常闭合 -->
        </el-form-item>

        <!-- 登录按钮：修复标签闭合 -->
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleLogin" :loading="loading">
            登录
          </el-button> <!-- 双标签正常闭合 -->
          <div class="register-link">
            还没有账号？<el-link type="primary" @click="toRegister">立即注册</el-link>
          </div>
        </el-form-item>
      </el-form> <!-- el-form 双标签正常闭合 -->
    </div>

    <!-- 页脚信息 -->
    <div class="login-footer">
      <p>Copyright © 学生管理系统 2026-11-11</p>
    </div>
  </div>
</template>

<script setup>
// 1. 导入核心依赖
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton, ElCheckbox, ElLink } from 'element-plus';
import { useRouter } from 'vue-router';
import { User, Lock } from '@element-plus/icons-vue';  // 导入图标组件
// 2. 导入登录接口
import { login } from '@/api/user';

// 组件挂载时添加进入动画
onMounted(() => {
  const loginCard = document.querySelector('.login-card');
  if (loginCard) {
    loginCard.style.opacity = '0';
    loginCard.style.transform = 'scale(0.9)';
    
    setTimeout(() => {
      loginCard.style.transition = 'all 0.5s cubic-bezier(0.4, 0, 0.2, 1)';
      loginCard.style.opacity = '1';
      loginCard.style.transform = 'scale(1)';
    }, 100);
  }
});

// 3. 登录表单数据（响应式）
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
});

// 4. 表单验证规则
const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度需在 3-20 个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名仅支持字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需在 6-20 个字符之间', trigger: 'blur' }
  ]
});

// 5. 表单引用 + 加载状态
const loginFormRef = ref(null);
const loading = ref(false);
const router = useRouter();

// 眼部跟踪相关
const leftEye = ref(null);
const rightEye = ref(null);
const mouseX = ref(0);
const mouseY = ref(0);
const isPasswordFocused = ref(false);

// 计算瞳孔位置
const calculatePupilPosition = (eyeElement, mouseX, mouseY) => {
  if (!eyeElement) return { x: 0, y: 0 };

  const eyeRect = eyeElement.getBoundingClientRect();
  const eyeCenterX = eyeRect.left + eyeRect.width / 2;
  const eyeCenterY = eyeRect.top + eyeRect.height / 2;

  // 计算鼠标相对于眼睛中心的角度
  const angle = Math.atan2(mouseY - eyeCenterY, mouseX - eyeCenterX);

  // 计算瞳孔移动的距离（限制在眼球范围内）
  const distance = Math.min(8, Math.hypot(mouseX - eyeCenterX, mouseY - eyeCenterY) / 10);

  // 计算瞳孔的最终位置
  const pupilX = Math.cos(angle) * distance;
  const pupilY = Math.sin(angle) * distance;

  return { x: pupilX, y: pupilY };
};

// 左眼瞳孔位置
const leftPupilStyle = computed(() => {
  if (isPasswordFocused.value) {
    // 输入密码时闭眼
    return {
      transform: 'translate(-50%, -50%) scaleY(0.1)',
      height: '2px',
      borderRadius: '50% / 10px'
    };
  }
  const position = calculatePupilPosition(leftEye.value, mouseX.value, mouseY.value);
  return {
    transform: `translate(calc(-50% + ${position.x}px), calc(-50% + ${position.y}px))`
  };
});

// 右眼瞳孔位置
const rightPupilStyle = computed(() => {
  if (isPasswordFocused.value) {
    // 输入密码时闭眼
    return {
      transform: 'translate(-50%, -50%) scaleY(0.1)',
      height: '2px',
      borderRadius: '50% / 10px'
    };
  }
  const position = calculatePupilPosition(rightEye.value, mouseX.value, mouseY.value);
  return {
    transform: `translate(calc(-50% + ${position.x}px), calc(-50% + ${position.y}px))`
  };
});

// 处理鼠标移动
const handleMouseMove = (event) => {
  mouseX.value = event.clientX;
  mouseY.value = event.clientY;
};

// 处理密码输入框焦点
const handlePasswordFocus = () => {
  isPasswordFocused.value = true;
};

const handlePasswordBlur = () => {
  isPasswordFocused.value = false;
};

// 6. 前往注册页
const toRegister = () => {
  // 添加展开动画效果
  const loginCard = document.querySelector('.login-card');
  if (loginCard) {
    loginCard.style.transition = 'all 0.5s cubic-bezier(0.4, 0, 0.2, 1)';
    loginCard.style.transform = 'scale(1.05)';
    loginCard.style.opacity = '0.8';
    
    setTimeout(() => {
      router.push('/register').catch(() => { });  // 忽略重复跳转警告
    }, 300);
  } else {
    router.push('/register').catch(() => { });  // 忽略重复跳转警告
  }
};

// 7. 登录处理函数
const handleLogin = async () => {
  // 表单验证
  if (!loginFormRef.value) {
    return ElMessage.error('表单加载中，请稍后再试');
  }
  try {
    await loginFormRef.value.validate();
  } catch (error) {
    return ElMessage.error('请完善并修正表单信息');
  }

  // 显示加载状态
  loading.value = true;

  try {
    // 调用登录接口
    const response = await login({
      username: loginForm.username,
      password: loginForm.password
    });

    // 1. 安全获取 data（避免 response.data 为 undefined）
    const { data = {} } = response;

    // 2. 过滤掉明文密码（前端不需要，且安全风险高）
    const { password, ...safeData } = data;

    // 3. 处理 token 为 null 的情况
    const { token } = response;
    const {id}=response;
    if (!token) {
      throw new Error('登录成功，但未获取到认证 token（后端返回 token: null），请联系后端修复');
    }

    localStorage.setItem('token', token);
    localStorage.setItem('userId',id);
    // 记住我：存储7天有效期
    if (loginForm.rememberMe) {
      const expireTime = new Date().getTime() + 7 * 24 * 60 * 60 * 1000;
      localStorage.setItem('tokenExpire', expireTime.toString());
    }

    ElMessage.success('登录成功，即将跳转首页...');
    setTimeout(() => {
      router.push('/').catch(() => { });
    }, 1000);

  } catch (error) {
    // 处理登录失败
    console.log('---');
    const errorMsg = error.response?.data?.message || error.message || '登录失败，请检查账号密码或网络';
    ElMessage.error(errorMsg);
  } finally {
    // 关闭加载状态
    loading.value = false;
  }
};
</script>

<style scoped>
/* 登录页面基础样式 */
.login-page {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  position: fixed;
  top: 0;
  left: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  margin: 0;
  overflow: hidden;
}

/* 背景图片 */
.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('/background_image.jpg');
  background-size: cover;
  background-position: center;
  filter: brightness(0.7);
  z-index: -1;
}

/* 品牌信息 */
.brand-info {
  position: fixed;
  top: -5%;
  left: 20px;
  color: #ffffff;
  text-align: left;
  z-index: 10;
}

.brand-logo {
  width: 200px;
  height: 200px;
  margin-bottom: 10px;
  border-radius: 8px;
}

.brand-slogan .slogan-text {
  font-size: 36px;
  font-weight: bold;
  margin: 0 0 10px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.brand-slogan .slogan-subtitle {
  font-size: 18px;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

/* 登录卡片样式 - 透明风格 */
.login-card {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  border-radius: 12px;
  background-color: rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
  position: relative;
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(255, 254, 254, 0.5);
  transform-origin: center;
}

.login-card:hover {
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
  background-color: rgba(255, 255, 255, 0.4);
}

/* 登录卡片动画类 */
.login-card.expand {
  animation: expandAnimation 0.5s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}

@keyframes expandAnimation {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.9;
  }
  100% {
    transform: scale(1.05);
    opacity: 0.8;
  }
}

/* 登录头部样式 */
.login-header {
  text-align: center;
  margin-bottom: 35px;
}

.login-title {
  font-size: 28px;
  font-weight: bold;
  color: #ffffff;
  margin: 0;
  text-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);
  letter-spacing: 1px;
}

/* 表单样式 */
.login-form {
  width: 100%;
}

/* 登录按钮样式 */
.login-btn {
  width: 100%;
  height: 46px;
  font-size: 17px;
  font-weight: 600;
  background-color: #409EFF;
  border: none;
  color: white;
  border-radius: 8px;
  transition: all 0.3s ease;
  letter-spacing: 1px;
}

.login-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 3px 12px rgba(64, 158, 255, 0.4);
}

.login-btn.is-disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 表单项间距 */
.login-form .el-form-item {
  margin-bottom: 20px;
}

/* 表单标签样式 */
.login-form .el-form-item__label {
  color: #ffffff;
  font-weight: 500;
  font-size: 14px;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  letter-spacing: 0.5px;
}

/* 登录按钮样式 - 简洁风格 */
.login-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
  background-color: #409EFF;
  border: none;
  color: white;
  border-radius: 4px;
  transition: all 0.3s ease;
}

/* 注册链接样式 */
.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #ffffff;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  font-weight: 400;
}

/* 页脚信息 */
.login-footer {
  position: fixed;
  bottom: 20px;
  text-align: center;
  width: 100%;
  left: 0;
  z-index: 10;
}

.login-footer p {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
  font-weight: 300;
}

/* 复选框样式 */
.login-form .el-checkbox {
  color: #ffffff;
  font-size: 13px;
}

.login-form .el-checkbox__label {
  color: #ffffff;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  font-weight: 400;
}

/* 眼部跟踪效果样式 */
.eyes-container {
  position: relative;
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 20px;
  height: 50px; /* 固定容器高度 */
  pointer-events: none;
}

.eye {
  position: relative;
  width: 40px; /* 固定宽度 */
  height: 40px; /* 固定高度 */
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.9);
  border: 2px solid rgba(0, 0, 0, 0.3);
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.left-eye {
  /* 移除绝对定位，使用相对定位 */
}

.right-eye {
  /* 移除绝对定位，使用相对定位 */
}

.pupil {
  position: absolute;
  width: 16px; /* 固定瞳孔宽度 */
  height: 16px; /* 固定瞳孔高度 */
  background-color: #333;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.2s ease-out;
}

.pupil::after {
  content: '';
  position: absolute;
  width: 6px; /* 固定高光宽度 */
  height: 6px; /* 固定高光高度 */
  background-color: white;
  border-radius: 50%;
  top: 3px;
  left: 3px;
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .brand-info {
    position: fixed;
    top: 15px;
    left: 15px;
    text-align: left;
  }

  .brand-logo {
    width: 70px;
    height: 70px;
  }

  .brand-slogan .slogan-text {
    font-size: 22px;
  }

  .brand-slogan .slogan-subtitle {
    font-size: 13px;
  }

  .login-card {
    width: 90%;
    max-width: 400px;
    padding: 25px;
    background-color: rgba(255, 255, 255, 0.4);
  }

  .login-title {
    font-size: 24px;
  }

  /* 眼睛大小保持固定，不随屏幕大小变化 */
  .eye {
    width: 40px;
    height: 40px;
  }

  .pupil {
    width: 16px;
    height: 16px;
  }

  .pupil::after {
    width: 6px;
    height: 6px;
  }

  .login-footer {
    position: static;
    margin-top: 30px;
  }

  .login-footer p {
    color: #ffffff;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
  }
}

@media (max-width: 480px) {
  .login-page {
    padding: 20px;
  }

  .login-card {
    width: 100%;
    padding: 20px;
    border-radius: 8px;
  }

  .login-title {
    font-size: 20px;
  }

  .login-form .el-form-item {
    margin-bottom: 20px;
  }

  /* 眼睛大小保持固定，不随屏幕大小变化 */
  .eye {
    width: 40px;
    height: 40px;
  }

  .pupil {
    width: 16px;
    height: 16px;
  }

  .pupil::after {
    width: 6px;
    height: 6px;
  }
}

@media (max-width: 480px) {
  .login-page {
    padding: 15px;
  }

  .login-card {
    padding: 15px;
    border-radius: 6px;
  }

  .login-form .el-form-item {
    margin-bottom: 15px;
  }

  /* 眼睛大小保持固定，不随屏幕大小变化 */
  .eye {
    width: 40px;
    height: 40px;
  }

  .pupil {
    width: 16px;
    height: 16px;
  }

  .pupil::after {
    width: 6px;
    height: 6px;
  }
}
</style>